import React, { useEffect, useState } from "react";
import Note from "./Note";

import { db, loadCollection } from "../database";
import { Collection } from "lokijs";
const Notes = () => {
    // MVVM
    const [notes, setNotes] = useState([
      
    ])
    const destroyEntity = (entry) => { // 在页面删除的同时数据库也会更新
        // console.log(entity)
        // 不是这一项的就留下  filter
        // setState
        const _entities = notes.filter(
                item => item.$loki !== entry.$loki)
        // console.log(_entities)
        setNotes(_entities)
        
        loadCollection('notes')
            .then((Collection) => {
                Collection.remove(entry)
                db.saveDatabase()
            })
    } 
    const noteItems = notes.map(
        (note) =>
         <Note 
            key={note.$loki}
            entity={note}
            destroyEntity={destroyEntity}
        />
    )
        
    const createEntity = () => {

    }

    // useEffect()
    // 先把页面模板显示出来，静态部分先显示出来  JSX -> babel + html+css渲染 需要花时间  组件挂载及渲染时间
    // 从数据库里去取  useEffect    无法保证谁先执行完
    // setNotes  列表出来  响应
    // console.log('++++++')
    const getInitialData = () => { // 往数据库中插入数据，并更新到 setNotes
        loadCollection('notes')
            .then((Collection) => {
                // console.log(Collection)
                // Collection.insert([
                //     {body: 'hello~'},
                //     {body: '你好~'}
                // ])
                const entities = Collection.chain()
                    .find() // select* from ..
                    .simplesort('$loki', 'isdesc') // 排序
                    .data()
                // console.log(entities)
                setNotes(entities)
            })
    }
    useEffect(() => {
        // 组件挂载后执行  生命周期
        // console.log('------')
        getInitialData() // 数据库
    }, [])
    return (
        <div className="ui container notes">
            <h4 className="ui horizontal divider header">
                <i className="paw icon"/>
                Notes App_React.js
            </h4>
            <button 
                className="ui right floated basic violet button"
                onClick={createEntity}>
                添加笔记
            </button>
            <div className="ui divided items">
                {noteItems}
            </div>
        </div>
    )
}

export default Notes;